package util;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class DEMO3 {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            MysqlDataSource mysqlDataSource=new MysqlDataSource();
            mysqlDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/java114?characterEncoding=utf8"
                    +"&allowPublicKeyRetrieval=true&useSSL=false" );
            mysqlDataSource.setUser("root");
            mysqlDataSource.setPassword("zyh22730267");
            DataSource dataSource=mysqlDataSource;
            connection=dataSource.getConnection();
            String sql="select id,name,sno,age,gender,enroll_date,class_id from student where name=?";
            preparedStatement=connection.prepareStatement(sql);
            System.out.println("请输入你要查询学生的姓名");
            String inName=scanner.nextLine();
            preparedStatement.setString(1,inName);
            resultSet=preparedStatement.executeQuery();
            while(resultSet.next()){
                long id=resultSet.getLong(1);
                String name=resultSet.getString(2);
                String sno=resultSet.getString(3);
                int age=resultSet.getInt(4);
                byte gender=resultSet.getByte(5);
                Date enroll_date=resultSet.getDate(6);
                long class_id =resultSet.getLong(7);
                System.out.println(MessageFormat.format("学生id:{0} 姓名:{1} 学号：{2} 年龄：{3} 性别：{4} 入学时间：{5} 班级编号：{6}",
                        id,name,sno,age,gender,enroll_date,class_id));
            }



        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            scanner.close();
        }
    }
}
